#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <limits.h>
#include "msgq.h"
#include "tools.h"

Ctos ctos;
Stoc stoc;

void login(void)
{
	
	char path[PATH_MAX];
	sprintf(path,"%s/%u",ACC_PATH,ctos.acc.id);
		
	pf("登陆账号:%s\n",path);
	int fd = open(path,O_RDWR);
	Ctos login;	
	read(fd,&login.acc,sizeof(login.acc));
	if(ERROR == fd)
	{
		perror("login");
		strcpy(stoc.str,"登陆失败,请检查账号是否存在...");
	}

	else
	{	

		if(login.acc.pass==ctos.acc.pass)
		{	
			login.acc.errno=0;
			sprintf(stoc.str,"登陆成功");	
		}
		if(login.acc.pass!=ctos.acc.pass)
		{	
			login.acc.errno++;
			sprintf(stoc.str,"登陆失败,还剩%d次机会",3-login.acc.errno);
		}
		if(login.acc.errno>3) 
		{
			sprintf(stoc.str,"账号被锁定，请先解锁");
		}
	
	}
	lseek(fd,0,SEEK_SET);
	write(fd,&login.acc,sizeof(login.acc));
	close(fd);
	// 返回登陆成功信息
	stoc_send(&stoc);
}

int main()
{
	init_msgq();
	for(;;)
	{
		ctos_recv(&ctos,TYPE_LOGIN);
		stoc.type = ctos.pid;
		login();
	}
}
